﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using Srvtools;


public partial class WorkTimeN_WorkONCalendar : System.Web.UI.UserControl
{

    private string _EmpId;
    private string _st;
    private string _et;
    private bool _IsSelectDateTime;

    public bool IsSelectDateTime
    {
        get
        {
            return _IsSelectDateTime;
        }
        set
        {
            _IsSelectDateTime = value;
        }
    }
    public string st
    {
        get
        {
            return _st;
        }
        set
        {
            _st = value;
        }
    }
    public string et
    {
        get
        {
            return _et;
        }
        set
        {
            _et = value;
        }
    }
    public string EmpId
    {
        get
        {
            return _EmpId;
        }
        set
        {
            _EmpId = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

        }
        catch
        {
        }
    }

    #region BindCalr
    private Hashtable EmpWorkOnDateTable;
    private Hashtable CompWorkDateDefine;
    private Hashtable EmpOverTimeDateTable;
    private DataTable EmpAddUp;
    private DataTable SpecialWorkTime;

    private bool IsDayWork = false;
    private string StartWorkOn;
    private string EndWorkOn;
    private string LateOfStartTime;
    private string LeaveOfEndTime;

    private DateTime FirstDayOfThisMonth;
    private DateTime LastDayOfThisMonth;


    //GetWorkTime_AddUpList
    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        try
        {
            if ((FirstDayOfThisMonth <= e.Day.Date) && (LastDayOfThisMonth >= e.Day.Date))
            {
                e.Cell.VerticalAlign = VerticalAlign.Top;
                string DKey = e.Day.Date.Year.ToString().Trim() + "-" + e.Day.Date.Month.ToString().Trim() + "-" + e.Day.Date.Day.ToString().Trim();
                bool NowIsWorkingDay = IsWorkingDay(e.Day.Date);
                string ShowText = "<span style=' text-align:left'><br/><br/>";

                //考勤汇总数据
                DataRow[] drs = EmpAddUp.Select("Wyear=" + e.Day.Date.Year + " and Wmonth=" + e.Day.Date.Month + " and Wday=" + e.Day.Date.Day);
                double daynum = 0;
                foreach (DataRow dr in drs)
                {
                    ShowText += " + " + dr["LeaveTypeName"].ToString() + " " + dr["WaddHour"].ToString() + " 小时<br/>";
                    daynum += Convert.ToDouble(dr["WaddHour"].ToString());
                }


                e.Cell.BorderColor = System.Drawing.Color.Black;
                e.Cell.BorderWidth = 1;
                e.Cell.BorderStyle = BorderStyle.Solid;

                //考勤小时
                double dwh = 0;
                string checkintime = "";

                //是否工作日
                if (IsDayWork)
                {
                    dwh = DayWorkHours((DateTime[])EmpWorkOnDateTable[DKey], out checkintime);

                }
                else
                {
                    dwh = SpecialWorkHours((DateTime[])EmpWorkOnDateTable[DKey], (DateTime[])EmpWorkOnDateTable[Convert.ToDateTime(DKey).AddDays(1).ToString("yyyy-M-d")], out checkintime);
                }
                if (dwh > 0)
                {
                    daynum += dwh;
                    if (daynum == 8)
                    {

                        ShowText += " 有正常考勤<br/>";
                    }
                    else
                    {
                        ShowText += " + 有考勤" + dwh + " 小时<br/>";
                    }
                }
                else if (dwh == -1)
                {
                    if (daynum == 0)
                    {
                        daynum = -1;
                    }

                }

                if (daynum >= 7.8)
                {
                    e.Cell.BackColor = System.Drawing.Color.LightGray;
                }
                else
                {
                    if (NowIsWorkingDay) //非工作日
                    {
                        if (daynum == 0)
                        {
                            e.Cell.BackColor = System.Drawing.Color.Yellow;
                            ShowText += " 无考勤记录 <br/>";
                        }
                        else if (daynum == -1)
                        {
                            e.Cell.BackColor = System.Drawing.Color.GreenYellow;
                            ShowText += " 只有一次考勤<br/>";
                        }
                        else
                        {
                            e.Cell.BackColor = System.Drawing.Color.GreenYellow;
                            ShowText += " + 缺工作时间 <span style='color:red'>" + (8 - daynum).ToString() + "</span> 小时<br/>";
                        }
                    }
                }

                ShowText += checkintime;

                if (NowIsWorkingDay == false) //非工作日
                {
                    e.Cell.BackColor = System.Drawing.Color.Tomato;
                }

                e.Cell.Controls.Add(new LiteralControl(ShowText + "</span>"));
            }
        }
        catch
        {
        }
    }

    private double DayWorkHours(DateTime[] DtIn, out string checkintime)
    {
        if (DtIn == null)
        {
            checkintime = "";
            return 0;
        }
        else
        {
            DateTime cutWs = Convert.ToDateTime(DtIn[0].ToString("yyyy-MM-dd") + " " + LateOfStartTime + ":00");
            DateTime cutWe = Convert.ToDateTime(DtIn[0].ToString("yyyy-MM-dd") + " " + EndWorkOn + ":00");

            return WorkHours(DtIn, cutWs, cutWe, out checkintime);
        }
        //return LackHours =0= 8 ? 8 : LackHours;
        //return Convert.ToInt32(Math.Ceiling(eet.Subtract(sst).TotalHours)) >= 8;
    }

    private double SpecialWorkHours(DateTime[] DtInToday, DateTime[] DtInTomorrow, out string checkintime)
    {
        checkintime = "";

        //考勤相差小于10 正确考勤记录
        DateTime[] dts = new DateTime[2];
        if (DtInToday == null)
        {
            return 0;
        }
        DateTime sst = DtInToday[0];
        DateTime eet = DtInToday[1];
        double ct = eet.Subtract(sst).TotalHours;
        if (ct <= 10 && ct != 0)
        {
            dts[0] = sst;
            dts[1] = eet;
        }
        else
        {
            if (DtInTomorrow == null)
            {
                return 0;
            }
            sst = DtInToday[1];
            eet = DtInTomorrow[0];
            ct = eet.Subtract(sst).TotalHours;
            if (ct <= 10 && ct != 0)
            {
                dts[0] = sst;
                dts[1] = eet;
            }
        }

        //套上班时间
        foreach (DataRow dr in SpecialWorkTime.Rows)
        {
            DateTime st = new DateTime();
            DateTime et = new DateTime();

            //套上班时间相同
            st = Convert.ToDateTime(dts[0].ToString("yyyy-MM-dd") + " " + dr["st"] + ":00");
            et = Convert.ToDateTime(dts[0].ToString("yyyy-MM-dd") + " " + dr["sct"] + ":00");
            if (dts[0].CompareTo(st) >= 0 & dts[0].CompareTo(et) <= 0)
            {
                return WorkHours(dts, Convert.ToDateTime(dts[0].ToString("yyyy-MM-dd") + " " + dr["sct"] + ":00"),
                    Convert.ToDateTime(dts[1].ToString("yyyy-MM-dd") + " " + dr["et"].ToString() + ":00"), out checkintime);
            }

            //套下班时间相同
            st = Convert.ToDateTime(dts[1].ToString("yyyy-MM-dd") + " " + dr["ect"] + ":00");
            et = Convert.ToDateTime(dts[1].ToString("yyyy-MM-dd") + " " + dr["et"] + ":00");
            if (dts[1].CompareTo(st) >= 0 & dts[1].CompareTo(et) <= 0)
            {
                return WorkHours(dts, Convert.ToDateTime(dts[0].ToString("yyyy-MM-dd") + " " + dr["sct"] + ":00"),
                    Convert.ToDateTime(dts[1].ToString("yyyy-MM-dd") + " " + dr["et"].ToString() + ":00"), out checkintime);
            }
        }
        if (DtInToday[0] != null)
        {
            return -1;
        }
        else
        {
            return 0;
        }
    }

    /// <summary>
    /// 获取考勤时间
    /// </summary>
    /// <param name="DtIn">考勤时间 早晚</param>
    /// <param name="cutWs">考勤规定最晚上班时间</param>
    /// <param name="cutWe">考勤规定最早下班时间</param>
    /// <returns></returns>
    private double WorkHours(DateTime[] DtIn, DateTime cutWs, DateTime cutWe, out string checkintime)
    {


        DateTime sst = DtIn[0];
        DateTime eet = DtIn[1];

        double LackHours = 0;
        LackHours += sst.Subtract(cutWs).TotalHours >= 0 ? sst.Subtract(cutWs).TotalHours : 0;
        LackHours += eet.Subtract(cutWe).TotalHours >= 0 ? 0 : cutWe.Subtract(eet).TotalHours;

        checkintime = "<br/><span style='color:blue'>" + sst + " 至 " + eet + "</span>";
        if (LackHours == 0)
        {
            return 8;
        }
        else
        {
            return Math.Round(8 - LackHours, 1);
        }
    }

    /// <summary>
    /// 取得本月某员工的的考勤和公司日期定义日的集合
    /// </summary>
    /// <param name="EmpId">员工工号</param>
    /// <param name="DateS">本月起始日</param>
    /// <param name="DataE">本月终止日</param>
    private void GetData(string EmpId, string DateS, string DataE)
    {
        try
        {
            //GetWorkOnType
            object[] myRet4 = CliUtils.CallMethod("SWorkTime", "GetWorkOnType", new object[] { "WorkTime_WorkOnTypeGroup.EmployeeId=" + EmpId });
            if (myRet4 != null)
            {
                if (myRet4[1].ToString() == "N")
                {
                    if (((DataSet)myRet4[2]).Tables[0] != null && ((DataSet)myRet4[2]).Tables[0].Rows.Count > 0)
                    {
                        DataRow dr = ((DataSet)myRet4[2]).Tables[0].Rows[0];

                        StartWorkOn = dr["st"].ToString();
                        EndWorkOn = dr["et"].ToString();
                        LateOfStartTime = dr["sct"].ToString();
                        LeaveOfEndTime = dr["ect"].ToString();
                    }
                    IsDayWork = true;
                }
                else
                {
                    IsDayWork = false;
                    SpecialWorkTime = ((DataSet)myRet4[2]).Tables[0];
                }
            }

            //本月考勤记录
            object[] objParam = new object[3];
            objParam[0] = EmpId;
            objParam[1] = Convert.ToDateTime(DateS).ToString("yyyy-MM-dd 00:00:00");
            objParam[2] = Convert.ToDateTime(DataE).AddDays(1).ToString("yyyy-MM-dd");
            object[] myRet = CliUtils.CallMethod("SWorkTime", "GetEmpWorkOnDateTable", objParam);
            if (myRet != null && (int)myRet[0] == 0)
            {
                EmpWorkOnDateTable = (Hashtable)myRet[1];
            }

            //本月节假日
            object[] objParam2 = new object[2];
            objParam2[0] = Convert.ToDateTime(DateS).ToString("yyyy-MM-dd 00:00:00");
            objParam2[1] = Convert.ToDateTime(DataE).ToString("yyyy-MM-dd 23:59:59");
            object[] myRet2 = CliUtils.CallMethod("SWorkTime", "GetCompWorkDateDefine", objParam2);
            if (myRet2 != null && (int)myRet2[0] == 0)
            {
                CompWorkDateDefine = (Hashtable)myRet2[1];
            }

            //本月考勤汇总
            object[] objParam3 = new object[1];
            string st = Convert.ToDateTime(DateS).ToString("yyyy-MM-dd 00:00:00");
            string et = Convert.ToDateTime(DataE).ToString("yyyy-MM-dd 23:59:59");

            objParam3[0] = " 1=1 and WorkTime_AddUp.EmployeeId = " + EmpId + " and cast(cast(Wyear as varchar(4))+'-'+cast(Wmonth as varchar(2))+'-'+cast(Wday as varchar(2))as datetime) >='" +
                st + "' and cast(cast(Wyear as varchar(4))+'-'+cast(Wmonth as varchar(2))+'-'+cast(Wday as varchar(2))as datetime) <='" + et + "'";

            object[] myRet3 = CliUtils.CallMethod("SWorkTime", "GetWorkTime_AddUpList", objParam3);
            if (myRet3 != null && myRet3[1] != null)
            {
                EmpAddUp = ((DataSet)myRet3[1]).Tables[0];
            }
        }
        catch
        {
        }
    }



    /// <summary>
    /// 判断是否为工作日
    /// </summary>
    /// <param name="Inday"></param>
    /// <returns></returns>
    private bool IsWorkingDay(DateTime Inday)
    {
        string DKey = Inday.Year.ToString().Trim() + "-" + Inday.Month.ToString().Trim() + "-" + Inday.Day.ToString().Trim();
        if (Inday.DayOfWeek == DayOfWeek.Saturday || Inday.DayOfWeek == DayOfWeek.Sunday)
        {
            if (CompWorkDateDefine.ContainsKey(DKey) == false)
            {
                return false;
            }
            else
            {
                object[] DtIn = (object[])CompWorkDateDefine[DKey];// { DTyp, DatePrepty };
                bool Dbk = (bool)DtIn[0];
                return Dbk;
            }
        }
        else
        {
            if (CompWorkDateDefine.ContainsKey(DKey) == false)
            {
                return true;
            }
            else
            {
                object[] DtIn = (object[])CompWorkDateDefine[DKey];// { DTyp, DatePrepty };
                bool Dbk = (bool)DtIn[0];
                return Dbk;
            }
        }

    }

    #endregion

    protected void Calendar1_PreRender(object sender, EventArgs e)
    {
        GetData(EmpId, st, et);
        Calendar1.VisibleDate = Convert.ToDateTime(st);
        FirstDayOfThisMonth = Convert.ToDateTime(st);
        LastDayOfThisMonth = Convert.ToDateTime(et);
        Calendar1.ShowNextPrevMonth = IsSelectDateTime;

        Calendar1.DataBind();
    }
}
